<template>
  <div class="container">
    <!-- 原文件 -->
    <div class="file-box" v-loading="loading">
      <div class="title">原{{ fileType(isFileType, isRequirementID, "").content }}文件：</div>
      <div>
        <p v-if="(oldFilesList.length) == 0">无</p>
        <el-tag style="cursor: pointer;margin-right: 5px;" v-model="oldFilesList" v-for="(tag, index) in oldFilesList"
          :key="index" closable="true" type="primary" @close="handleDelFile(tag.url)"
          @click="handleDownloadFile(tag, baseUrl)">
          {{ tag.fileName }}
        </el-tag>
      </div>
    </div>

    <!-- 修改后的文件 -->
    <div class="files-box">
      <div class="file-box-1">
        <div class="title">追加文件：</div>
        <div class="file-btn">
          <div style="width: 50%;margin-right: 10px;border-right: 1px solid #ccc; ">
            <el-button class="upload-btn" type="primary" size="small" @click="openModal = true">关联文件</el-button>
            <!-- 关联文件 -->
            <div style="margin-top: 10px;width: 100%;display: flex;flex-direction: column;flex-wrap: wrap;">
              <el-tag style="margin-bottom: 5px;display: flex;justify-content: space-between;margin-right: 10px;"
                v-for="(file, index) in newAssFilesList" :key="index" closable :disable-transitions="false"
                @close="handleDelAssFile(file)">
                {{ handleFileName(file).fileName }}
              </el-tag>
            </div>
          </div>
          <div style="border-left: 1px solid #ccc; width: 50%; padding-left: 10px;">
            <!-- <el-upload class="upload-demo" style="margin-left: 10px;" v-model:file-list="newFilesListText" action=""
              multiple="true" :http-request="handleUpLoad" :on-success="handleSuccess" :on-error="handleError"
              :on-remove="handleRemove">
              <el-button class="upload-btn" type="primary" size="small">上传文件</el-button>
            </el-upload> -->

            <UploadFilesVue :initConfig="initConfig" @updateFilePaths="handleUpdateFilePaths" :resetFiles="resetFiles">
            </UploadFilesVue>

          </div>
        </div>
      </div>
      <!-- 关联文件 -->
      <!--  <div>
         <el-tag
          v-for="(file, index) in newAssFilesList"
          :key="index"
          closable
          :disable-transitions="false"
        >
          {{ handleFileName(file).fileName }}
        </el-tag>
      </div> -->
    </div>

    <!-- 关联文件 -->
    <div>
      <AssRequiremenFileVue v-model:isOpen="openModal" @add-files="handleAddFiles"></AssRequiremenFileVue>
    </div>

    <div class="opera-box">
      <el-button type="default" @click="handleColseEditFile">取消</el-button>
      <el-button type="primary" @click="handleSubmitEditFile">确定</el-button>
    </div>
  </div>
</template>

<script setup lang='ts'>
import { ref, reactive, PropType, watch } from 'vue';
import { handleDownloadFile, fileType, handleFileName } from "@/utils/utils";
import { postUploadFile } from "@/api/common/index";
import { ElMessage } from "element-plus";
import { handleUploadRequirement } from '@/utils/common';
import AssRequiremenFileVue from './assRequiremenFile.vue';
import UploadFilesVue from "@/components/requirement/uploadFiles.vue";


const emit = defineEmits(['edit-file']);
const props = defineProps({
  isRequirementID: {
    type: Number as PropType<any>,
    required: true,
  },
  isChildId: {
    type: Number as PropType<any>,
    required: true,
  },
  filesList: {
    type: Array as PropType<any>,
    required: true,
    default: () => ({
      fileName: "",
      name: "",
      timestamp: "",
      type: "",
      url: "",
    })
  },
  isEditFileType: {
    type: Number,
    required: true
  }
});

const loading = ref(false);
const baseUrl = ref("");
const isRequirementID = ref<any>(null);
const isChildId = ref<any>(null);
const isFileType = ref<any>(null);
const oldFilesList = ref<any>([]);// 已上传的文件
const newFilesList = ref<any>([]);// 新添加的文件
const newFilesListText = ref<any>([]);// 新添加的文件名
const files = ref("");// 修改后的文件列表
const newAssFilesList = ref<any>([]);// 新关联的文件

// * 上传文件初始配置
const initConfig = ref({
  tipText: "",// 提示文本
  type: "primary",// 按钮类型
  plain: true,// 按钮样式
  btnText: "上传",// 按钮文本
  fileUrl: "/file/upload_file",// 上传地址
  fileType: "summaryPath",// 上传类型
  fileTypeId: "5",// 上传类型id
});
const resetFiles = ref(false);// 是否清除已上传文件列表


watch(() => props, (newData, oldData) => {
  if (newData !== oldData) {
    isRequirementID.value = props.isRequirementID;
    isFileType.value = props.isEditFileType;
    oldFilesList.value = props.filesList;
    isChildId.value = props.isChildId;

    if (props.isEditFileType > 2) {
      isRequirementID.value = props.isChildId;
    } else {
      isRequirementID.value = props.isRequirementID;
    }
    console.log("当前接受数据：", fileType(isFileType.value, isRequirementID, "").text);

    initConfig.value = {
      tipText: "",// 提示文本
      type: "primary",// 按钮类型
      plain: false,// 按钮样式
      btnText: "上传文件",// 按钮文本
      fileUrl: "/file/upload_file",// 上传地址
      fileType: fileType(isFileType.value, isRequirementID, "").text,// 上传类型
      fileTypeId: "5",// 上传类型id
    }
    console.log("initConfig:", initConfig.value);
  }
}, { deep: true, immediate: true });


// TODO 删除附件
const handleDelFile = (val: any) => {
  const index = oldFilesList.value.findIndex((item: any) => item.url === val);
  if (index !== -1) {
    oldFilesList.value.splice(index, 1);
  }
};

// 接收子组件中上传的文件地址
const handleUpdateFilePaths = (value: any) => {
  newFilesList.value = value;
};

// TODO 取消修改
const handleColseEditFile = () => {
  newFilesList.value = [];
  oldFilesList.value = [];
  isChildId.value = null;
  isRequirementID.value = null;
  isFileType.value = null;
  resetFiles.value = true;
  setTimeout(() => {
    resetFiles.value = false;
  }, 100);

  emit("edit-file", false);
};

// TODO 确定修改，提交文件
const handleSubmitEditFile = async () => {
  if ((oldFilesList.value.length + newFilesList.value.length + newAssFilesList.value.length) == 0) {
    ElMessage.warning("至少包含一个文件！");
    return;
  } else {
    if (oldFilesList.value.length > 0 && newFilesList.value.length > 0 && newAssFilesList.value.length > 0) {
      files.value = oldFilesList.value.map((path: any) => path.url).join('|') + '|' + newFilesList.value.map((path: any) => path).join('|') + '|' + newAssFilesList.value.join('|');
    } else {
      if (oldFilesList.value.length === 0) {
        // 1、原文件为空
        if (newAssFilesList.value.length === 0) {
          files.value = (newFilesList.value.map((path: any) => path)).join('|');
        } else if (newFilesList.value.length === 0) {
          files.value = newAssFilesList.value.join('|');
        } else {
          files.value = newFilesList.value.map((path: any) => path).join('|') + '|' + newAssFilesList.value.join('|');
        }
      } else if (newFilesList.value.length === 0) {
        // 2、上传文件为空
        if (newAssFilesList.value.length === 0) {
          files.value = (oldFilesList.value.map((path: any) => path.url)).join('|');
        } else if (oldFilesList.value.length === 0) {
          files.value = newAssFilesList.value.join('|');
        } else {
          files.value = oldFilesList.value.map((path: any) => path.url).join('|') + '|' + newAssFilesList.value.join('|');
        }
      } else if (newAssFilesList.value.length === 0) {
        // 3、关联文件为空
        if (oldFilesList.value.length === 0) {
          files.value = (newFilesList.value.map((path: any) => path)).join('|');
        } else if (newFilesList.value.length === 0) {
          files.value = (oldFilesList.value.map((path: any) => path.url)).join('|');
        } else {
          files.value = oldFilesList.value.map((path: any) => path.url).join('|') + '|' + newFilesList.value.map((path: any) => path).join('|');
        }
      }
    }

    const aginFileForm = fileType(isFileType.value, isRequirementID.value, files.value).formData;

    await handleUploadRequirement(aginFileForm).then(async () => {
      oldFilesList.value = [];
      newFilesList.value = [];
      files.value = "";
      emit("edit-file", true);
    }).catch((error) => {
      ElMessage.error("上传失败！");
      throw console.error(error);
    });
  };
};

// TODO 开启关联文件弹窗
const openModal = ref(false);
// 监听子组件的事件函数，并接收子组件中选中的文件
const handleAddFiles = (data: any) => {
  newAssFilesList.value = newAssFilesList.value.concat(data);
};
// 删除关联文件
const handleDelAssFile = (row: any) => {
  newAssFilesList.value.splice(newAssFilesList.value.indexOf(row), 1);
};

</script>
<style lang='scss' scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .file-box {
    width: 100%;
    min-height: 50px;
    display: flex;
    flex-direction: row;
    justify-content: left;
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #CDD0D6;
    border-radius: 10px;
  }

  .files-box {
    width: 100%;
    min-height: 50px;
    display: flex;
    flex-direction: column;
    border: 1px solid #CDD0D6;
    border-radius: 10px;
    margin-bottom: 10px;

    .file-box-1 {
      width: 100%;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      padding: 10px;

      .title {
        width: 80px;
        font-weight: bold;
      }

      .file-btn {
        width: 100%;
        display: flex;
        flex-direction: row;
        align-items: flex-start;
      }

    }
  }

  .opera-box {
    width: calc(100% - 80px);
    text-align: right;
  }
}
</style>